
object AnonymousFunctionsDemo extends App {
  case class StudentScore(name: String, scores: Map[String, Double])
  val studentScores = List(
    StudentScore("张三", Map("语文" -> 88.0, "数学" -> 95.0, "英语" -> 92.0)),
    StudentScore("李四", Map("语文" -> 76.0, "数学" -> 89.0, "英语" -> 90.0)),
    StudentScore("王五", Map("语文" -> 92.0, "数学" -> 85.0, "英语" -> 88.0)),
    StudentScore("赵六", Map("语文" -> 68.0, "数学" -> 72.0, "英语" -> 75.0))
  )

  def analyzeScores(
                     data: List[StudentScore],
                     analyzer: StudentScore => Double
                   ): List[(String, Double)] = {
    data.map(student => (student.name, analyzer(student)))
  }

  val totalScoreAnalyzer = (s: StudentScore) => s.scores.values.sum
  val averageScoreAnalyzer = (s: StudentScore) => s.scores.values.sum / s.scores.size

  println("=== 总分分析===")
  val totalScores = analyzeScores(studentScores, totalScoreAnalyzer)
  totalScores.foreach { case (name, score) =>
    println(s"$name: $score")
  }
  println("\n=== 平均分分析===")
  val averageScores = analyzeScores(studentScores, averageScoreAnalyzer)
  averageScores.foreach { case (name, score) =>
    println(f"$name: $score%.1f")
  }

  println("\n=== 语文成绩分析===")
  val chineseScores = analyzeScores(studentScores, s => s.scores.getOrElse("语文", 0.0))
  chineseScores.foreach { case (name, score) =>
    println(s"$name: $score")
  }

  println("\n=== 优秀学生筛选(平均分>=85)==")
  val excellentStudents = studentScores.filter { s =>
    val avg = s.scores.values.sum / s.scores.size
    avg >= 85
  }.map(_.name)
  println(s"优秀学生: ${excellentStudents.mkString(",")}")

  case class CourseEvaluation(courseName: String, studentName: String, rating: Double, comment: String)
  val courseEvaluations = List(
    CourseEvaluation("Scala编程", "张三", 4.8, "老师讲得很好，内容丰富"),
    CourseEvaluation("Scala编程", "李四", 4.2, "难度适中，讲解清晰"),
    CourseEvaluation("大数据导论", "王五", 3.5, "理论偏多，实践较少"),
    CourseEvaluation("大数据导论", "赵六", 4.0, "收获较大，推荐学习")
  )

  def analyzeEvaluations(
                          data: List[CourseEvaluation],
                          groupByFunc: CourseEvaluation => String,
                          statFunc: List[CourseEvaluation] => Double
                        ): Map[String, Double] = {
    data.groupBy(groupByFunc).map { case (key, group) =>
      (key, statFunc(group))
    }
  }

  println("\n=== 课程平均评分分析 ===")
  val courseAvgRating = analyzeEvaluations(
    courseEvaluations,
    _.courseName,
    group => group.map(_.rating).sum / group.size
  )
  courseAvgRating.foreach { case (course, rating) =>
    println(f"$course: $rating%.1f 分")
  }
}